import { createStore } from 'vuex'
import { ElLoading } from 'element-plus'

class ErrorVal {
    error
    warning
    constructor(error, warning) {
        this.error = error
        this.warning = warning
    }
}

const errorStore = createStore({
    state: () => ({
        errorList: new Array(),
        warning: false
    }),
    mutations: {
        aspectSync(state, execute, loadingText = '加载中···') {
            const loading = ElLoading.service({
                lock: true,
                text: loadingText,
                background: 'rgba(0, 0, 0, 0.7)',
            })
            try {
                execute()
            } catch (error) {
                state.errorList.push(error)
                state.warning = true
                alert(error)
                console.log(error)
            } finally {
                loading.close()
            }
        },
        pushError(state, val) {
            state.errorList.push(val.error)
            state.warning = val.warning
        },
        allClear(state) {
            state.warning = false
        },
        clear(state) {
            while (state.errorList.length > 0)
                state.errorList.pop();
        }
    },
    actions: {
        async aspect({ commit }, execute, loadingText = '加载中···') {
            const loading = ElLoading.service({
                lock: true,
                text: loadingText,
                background: 'rgba(0, 0, 0, 0.7)',
            })
            try {
                await execute()
            } catch (error) {
                commit('pushError', new ErrorVal(error, true))
                alert(error)
                console.log(error)
            } finally {
                loading.close()
            }
        }
    },
})

export default errorStore